const App = getApp();
const DEFAULT_PAGE = 0;
// 工具类
import Util from '../../utils/util.js';
Page({
  startPageX: 0,
  currentView: DEFAULT_PAGE,
  data: {
    // 页面参数
    options: {},
    // 页面元素
    items: {},
    activityList:[],
    scrollTop: 0,
    toView: `card_${DEFAULT_PAGE}`,
    noticeButtonActive:1, //1大区活动，2本队活动
    nowDate:Util.dateFormat('YYYY-mm-dd HH:MM:SS', new Date()),//当前时间
    peopleNum:1,
    showPopup:false,
    activity_id:"",
    userId:0,
    showIndex:false,
    env_status:1, //1，2审核切换使用
    bannerConfig:App.getConfig().index,
    shanghui_list:[], //已经加入的商会
    nameShowStatus:false,
    shanghui_id:0,
    topHeight:0,//头部高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 当前页面参数
    this.setData({
      options
    });
  },
  onShow(){
    // topheight
    this.getTopHeight()
    this.setData({
      userId:App.getUserId()//判断用户ID是否存在
    })
     // 加载页面数据
     this.getPageData();
  },
  getTopHeight(){
    const { statusBarHeight } = wx.getSystemInfoSync();
    console.log('statusBarHeight',statusBarHeight)
    const menuButtonObject = wx.getMenuButtonBoundingClientRect();
    const { top, height } = menuButtonObject;
    console.log(top,height)
    // 此高度基于右上角菜单在导航栏位置垂直居中计算得到
    const navBarHeight = height + (top - statusBarHeight) * 2;
    console.log('navBarHeight',navBarHeight)
    this.setData({
      topHeight:statusBarHeight+navBarHeight-40,
    })
  },
  /**
   * 加载页面数据
   */
  getPageData(callback) {
    let _this = this;
    App._get('page/index', {
      page_id: _this.data.options.page_id || 0,
      env_status:_this.data.env_status
    }, result => {
      // 设置顶部导航栏栏
      _this.setPageBar(result.data.page);
      _this.setData(result.data);
       wx.setStorageSync('isRegister', result.data.isRegister) //判断是否可以注册
      _this.setData({
        showIndex:result.data.showIndex,
        shanghui_list:result.data.shanghui_list,
        });
      if(_this.data.noticeButtonActive == 1){
        _this.setData({
          activityList:result.data.activity
        });
      }else{
        _this.setData({
          activityList:result.data.activity_team
        });
      }
      console.log(_this.data)
      // 回调函数
      typeof callback === 'function' && callback();
    });
  },
  
  /**
   * 设置顶部导航栏
   */
  setPageBar(page) {
    // 设置页面标题
    wx.setNavigationBarTitle({
      // title: page.params.title
       title: '叮当商协会'
    });
    // 设置navbar标题、颜色
    wx.setNavigationBarColor({
      frontColor: page.style.titleTextColor === 'white' ? '#ffffff' : '#000000',
      backgroundColor: page.style.titleBackgroundColor
    })
  },
 /**
   * 活动公告：大区活动/本地活动标签切换
   */ 
  noticeButtonActive(e){
    let active = e.currentTarget.dataset.id;
    if(this.data.noticeButtonActive != active){
      this.setData({
       noticeButtonActive: active,
       nowDate:Util.dateFormat('YYYY-mm-dd HH:MM:SS', new Date()),//当前时间
      });
    }
    if(this.data.noticeButtonActive == 1){
      this.setData({
        activityList:this.data.activity
      });
    }else{
      this.setData({
        activityList:this.data.activity_team
      });
    }
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    // 获取首页数据
    this.getPageData(function () {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage() {
    const _this = this;
    console.log("/pages/index/index?" + App.getShareUrlParams());
    return {
      title: _this.data.page.params.share_title,
      path: "/pages/index/index?" + App.getShareUrlParams()
    };
  },

  /**
   * 分享到朋友圈
   * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
   * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
   */
  onShareTimeline() {
    const _this = this;
    return {
      title: _this.data.page.params.share_title,
      path: "/pages/index/index?" + App.getShareUrlParams()
    };
  },
   //页面跳转
   pageTo(e){
    let url = e.currentTarget.dataset.value;
    wx.navigateTo({
      url:url
    })
  },
   //tab页面跳转
   pageTab(e){
    let url = e.currentTarget.dataset.value;
    wx.switchTab({
      url: url
    })
   },
   touchStart(){

   },
   touchEnd(){

  },
    // 报名弹窗
    onShowPopup(e){
      let that = this;
      console.log(e.currentTarget.dataset.id)
      that.setData({
        peopleNum:1,
        activity_id:e.currentTarget.dataset.id,
        showPopup: !that.data.showPopup
      }); 
    },
    /**
   * 自定义输入数量
   */
  onInputNum(e) {
    let _this = this,
      iptValue = e.detail.value;
    if (!Util.isPositiveInteger(iptValue) && iptValue !== '') {
      iptValue = 1;
    }
    _this.setData({
      peopleNum: iptValue
    });
  },
  /**
   * 增加数量
   */
  onIncNumber(e) {
    let _this = this;
    App.saveFormId(e.detail.formId);
    _this.setData({
      peopleNum: ++_this.data.peopleNum
    })
  },

  /**
   * 减少数量
   */
  onDecNumber(e) {
    let _this = this;
    App.saveFormId(e.detail.formId);
    if (_this.data.peopleNum > 1) {
      _this.setData({
        peopleNum: --_this.data.peopleNum
      });
    }
  },
  //报名提交
  formSubmit(e) {
    let formD = e.detail.value;//获取表单数据
    let formStatus = false
    for (let key in formD) {
      if(formD[key] == ""){
        formStatus = true
        break;
      }
    }
    if(formStatus){
      App.showError("姓名和电话不能空！");
      return;
    }
    let obj ={
      name:formD.userName,
      phone:formD.userTel,
      people_num:this.data.peopleNum|1,
      activity_id:this.data.activity_id
    }
    console.log(obj);
    let that =this
    App._post_form('activity/signup', obj, result => {
      //成功提示
      App.showSuccess(result.msg, function() {
        that.setData({
          showPopup: false
        }); 
        console.log("noticeButtonActive",that.data.noticeButtonActive)
        that.getPageData();
        console.log("noticeButtonActive2",that.data.noticeButtonActive)
      });
      
    });
  },
  /**
   * 订单提交成功后回调（微信支付调起）2023年5月24日 16:32:00   未使用
   */
  _onSubmitCallback(result) {
    let _this = this;
    // 订单创建成功后回调--微信支付
    if (result.code === -10) {
      App.showError(result.msg, () => {
        _this.redirectToOrderIndex();
      });
      return false;
    }
    // 发起微信支付
    App.wxPayment({
      payment: result.data.payment,
      success: res => {
        _this.redirectToOrderIndex();
      },
      fail: res => {
        App.showError(result.msg.error, () => {
          _this.redirectToOrderIndex();
        });
      },
    });
  },
  /**
   * 跳转到未付款订单
   */
  redirectToOrderIndex(url) {
    wx.redirectTo({
      url: '../order/index',
    });
  },
  // 预览领导风采人物图片
  preview(e){
    let imageUrl = e.currentTarget.dataset.id;
    wx.previewImage({
      current: imageUrl, // 当前显示图片的http链接
      urls: [imageUrl] // 需要预览的图片http链接列表
    })
  },
  searchShow(e){
    this.setData({
      nameShowStatus:!this.data.nameShowStatus, 
    })
  },
  // 切换商会
  checkSearch(e){
    let type = e.currentTarget.dataset.type;
    let shanghui_id = e.currentTarget.dataset.id;
    let that =this
    if(!type){
      App._post_form('shanghui/uphui', {shanghui_id}, result => {
        //成功提示
        App.showSuccess(result.msg, function() {
          that.setData({
            nameShowStatus:false, 
          }); 
          that.getPageData();
        });
        
      });
    }
  }
});